package com.ergou.easylive.admin.service.impl;

import com.ergou.easylive.admin.entity.dto.SysPermissionCreateDTO;
import com.ergou.easylive.admin.entity.dto.SysPermissionQueryDTO;
import com.ergou.easylive.admin.entity.dto.SysPermissionUpdateDTO;
import com.ergou.easylive.admin.entity.po.SysPermissions;
import com.ergou.easylive.admin.entity.vo.menu.MateEntity;
import com.ergou.easylive.admin.entity.vo.menu.MenuVO;
import com.ergou.easylive.admin.exception.AdminException;
import com.ergou.easylive.admin.mapper.SysPremissMapper;
import com.ergou.easylive.admin.service.SysPremissService;
import com.ergou.easylive.common.entity.response.Result;
import com.ergou.easylive.common.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限服务实现类(SysPremissService)
 *
 * @author Er-Gou
 * @date 2025-10-03 00:39
 */
@Slf4j
@Service
public class SysPremissServiceImpl implements SysPremissService {

    @Resource
    private SysPremissMapper sysPremissMapper;

    @Override
    public List<MenuVO> getMenuTree() {
        // 获取所有菜单权限
        List<SysPermissions> permissions = sysPremissMapper.selectAllMenuPermissions();

        if (permissions.isEmpty()) {
            return new ArrayList<>();
        }

        // 转换为MenuVO并按父级分组
        Map<Integer, List<SysPermissions>> groupedPermissions = permissions.stream()
                .collect(Collectors.groupingBy(SysPermissions::getParentId));

        // 构建菜单树
        return buildMenuTree(groupedPermissions, 0);
    }

    @Override
    public LinkedList<SysPermissions> getPremissionList() {
        LinkedList<SysPermissions> sysPermissions = sysPremissMapper.selectAllPermissions();
        return sysPermissions;
    }

    /**
     * 递归构建菜单树
     *
     * @param groupedPermissions 按父级分组的权限数据
     * @param parentId           父级ID
     * @return 菜单VO列表
     */
    private List<MenuVO> buildMenuTree(Map<Integer, List<SysPermissions>> groupedPermissions, Integer parentId) {
        List<SysPermissions> currentPermissions = groupedPermissions.get(parentId);
        if (currentPermissions == null || currentPermissions.isEmpty()) {
            return new ArrayList<>();
        }

        List<MenuVO> menuVOs = new ArrayList<>();
        for (SysPermissions permission : currentPermissions) {
            MenuVO menuVO = convertToMenuVO(permission);

            // 递归构建子菜单
            List<MenuVO> children = buildMenuTree(groupedPermissions, permission.getId());
            if (!children.isEmpty()) {
                menuVO.setChildren(new java.util.LinkedList<>(children));
            }

            menuVOs.add(menuVO);
        }

        return menuVOs;
    }

    /**
     * 将权限实体转换为菜单VO
     *
     * @param permission 权限实体
     * @return 菜单VO
     */
    private MenuVO convertToMenuVO(SysPermissions permission) {
        MenuVO menuVO = new MenuVO();
        menuVO.setPath(permission.getRoutePath());
        menuVO.setName(permission.getRouteName());
        menuVO.setComponent(permission.getComponentPath());

        // 设置Mate信息
        MateEntity meta = new MateEntity();
        meta.setTitle(permission.getRouteTitle());
        meta.setIcon(permission.getIcon());
        meta.setHidden(permission.getIsHidden() == 1);
        meta.setActiveRoute(permission.getActiveRoute());
        meta.setPermissionLevel(permission.getPermissionLevel());
        menuVO.setMeta(meta);

        return menuVO;
    }

    @Override
    public SysPermissions getById(Integer id) {
        if (id == null) {
            throw new AdminException(ResultCode.BAD_REQUEST, "权限ID不能为空");
        }
        return sysPremissMapper.selectById(id);
    }

    @Override
    public Result<Object> getPageList(SysPermissionQueryDTO queryDTO) {
        try {
            // 设置默认值
            if (queryDTO.getPageNum() == null || queryDTO.getPageNum() <= 0) {
                queryDTO.setPageNum(1);
            }
            if (queryDTO.getPageSize() == null || queryDTO.getPageSize() <= 0) {
                queryDTO.setPageSize(10);
            }

            // 计算偏移量
            int offset = (queryDTO.getPageNum() - 1) * queryDTO.getPageSize();
            queryDTO.setPageNum(offset);

            // 查询数据
            List<SysPermissions> permissions = sysPremissMapper.selectPageList(queryDTO);
            Long total = sysPremissMapper.selectCount(queryDTO);

            // 构建分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", permissions);
            result.put("total", total);
            result.put("pageNum", queryDTO.getPageNum() / queryDTO.getPageSize() + 1);
            result.put("pageSize", queryDTO.getPageSize());

            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询权限列表失败", e);
            return Result.fail("查询失败");
        }
    }

    @Override
    public Result<Object> create(SysPermissionCreateDTO createDTO) {
        try {
            // 参数校验
            validateCreateDTO(createDTO);

            // 检查权限名称是否已存在
            if (sysPremissMapper.checkPermissionNameExists(createDTO.getPermissionName(), null) > 0) {
                return Result.fail("权限名称已存在");
            }

            // 检查路由名称是否已存在
            if (StringUtils.hasText(createDTO.getRouteName()) && 
                sysPremissMapper.checkRouteNameExists(createDTO.getRouteName(), null) > 0) {
                return Result.fail("路由名称已存在");
            }

            // 构建权限实体
            SysPermissions permission = new SysPermissions();
            BeanUtils.copyProperties(createDTO, permission);
            permission.setIsDeleted(0);
            permission.setCreatedAt(LocalDateTime.now());
            permission.setUpdatedAt(LocalDateTime.now());

            // 设置默认值
            if (permission.getStatus() == null) {
                permission.setStatus(1);
            }
            if (permission.getIsHidden() == null) {
                permission.setIsHidden(0);
            }
            if (permission.getSortOrder() == null) {
                permission.setSortOrder(0);
            }

            int result = sysPremissMapper.insert(permission);
            if (result > 0) {
                log.info("新增权限成功，权限名称：{}", createDTO.getPermissionName());
                return Result.success("新增权限成功");
            } else {
                return Result.fail("新增权限失败");
            }
        } catch (AdminException e) {
            throw e;
        } catch (Exception e) {
            log.error("新增权限失败", e);
            return Result.fail("新增权限失败");
        }
    }

    @Override
    public Result<Object> update(SysPermissionUpdateDTO updateDTO) {
        try {
            // 参数校验
            validateUpdateDTO(updateDTO);

            // 检查权限是否存在
            SysPermissions existingPermission = sysPremissMapper.selectById(updateDTO.getId());
            if (existingPermission == null) {
                return Result.fail("权限不存在");
            }

            // 检查权限名称是否已存在（排除当前记录）
            if (StringUtils.hasText(updateDTO.getPermissionName()) && 
                sysPremissMapper.checkPermissionNameExists(updateDTO.getPermissionName(), updateDTO.getId()) > 0) {
                return Result.fail("权限名称已存在");
            }

            // 检查路由名称是否已存在（排除当前记录）
            if (StringUtils.hasText(updateDTO.getRouteName()) && 
                sysPremissMapper.checkRouteNameExists(updateDTO.getRouteName(), updateDTO.getId()) > 0) {
                return Result.fail("路由名称已存在");
            }

            // 构建权限实体
            SysPermissions permission = new SysPermissions();
            BeanUtils.copyProperties(updateDTO, permission);
            permission.setUpdatedAt(LocalDateTime.now());

            int result = sysPremissMapper.updateById(permission);
            if (result > 0) {
                log.info("更新权限成功，权限ID：{}", updateDTO.getId());
                return Result.success("更新权限成功");
            } else {
                return Result.fail("更新权限失败");
            }
        } catch (AdminException e) {
            throw e;
        } catch (Exception e) {
            log.error("更新权限失败", e);
            return Result.fail("更新权限失败");
        }
    }

    @Override
    public Result<Object> deleteById(Integer id) {
        try {
            if (id == null) {
                return Result.fail("权限ID不能为空");
            }

            // 检查权限是否存在
            SysPermissions permission = sysPremissMapper.selectById(id);
            if (permission == null) {
                return Result.fail("权限不存在");
            }

            // 检查是否有子权限
            List<SysPermissions> children = sysPremissMapper.selectByParentId(id);
            if (!CollectionUtils.isEmpty(children)) {
                return Result.fail("该权限下存在子权限，无法删除");
            }

            int result = sysPremissMapper.deleteById(id);
            if (result > 0) {
                log.info("删除权限成功，权限ID：{}", id);
                return Result.success("删除权限成功");
            } else {
                return Result.fail("删除权限失败");
            }
        } catch (Exception e) {
            log.error("删除权限失败", e);
            return Result.fail("删除权限失败");
        }
    }

    @Override
    public Result<Object> deleteByIds(List<Integer> ids) {
        try {
            if (CollectionUtils.isEmpty(ids)) {
                return Result.fail("权限ID列表不能为空");
            }

            // 检查是否有子权限
            for (Integer id : ids) {
                List<SysPermissions> children = sysPremissMapper.selectByParentId(id);
                if (!CollectionUtils.isEmpty(children)) {
                    return Result.fail("权限ID为" + id + "的权限下存在子权限，无法删除");
                }
            }

            int result = sysPremissMapper.deleteByIds(ids);
            if (result > 0) {
                log.info("批量删除权限成功，删除数量：{}", result);
                return Result.success("批量删除权限成功，共删除" + result + "条记录");
            } else {
                return Result.fail("批量删除权限失败");
            }
        } catch (Exception e) {
            log.error("批量删除权限失败", e);
            return Result.fail("批量删除权限失败");
        }
    }

    @Override
    public List<SysPermissions> getByParentId(Integer parentId) {
        if (parentId == null) {
            return new ArrayList<>();
        }
        return sysPremissMapper.selectByParentId(parentId);
    }

    /**
     * 校验创建DTO
     */
    private void validateCreateDTO(SysPermissionCreateDTO createDTO) {
        if (createDTO == null) {
            throw new AdminException(ResultCode.BAD_REQUEST, "创建参数不能为空");
        }

        if (!StringUtils.hasText(createDTO.getRouteTitle())) {
            throw new AdminException(ResultCode.BAD_REQUEST, "路由标题不能为空");
        }
        if (createDTO.getParentId() == null) {
            throw new AdminException(ResultCode.BAD_REQUEST, "父级权限ID不能为空");
        }
        if (createDTO.getPermissionLevel() == null) {
            throw new AdminException(ResultCode.BAD_REQUEST, "权限等级不能为空");
        }
    }

    /**
     * 校验更新DTO
     */
    private void validateUpdateDTO(SysPermissionUpdateDTO updateDTO) {
        if (updateDTO == null) {
            throw new AdminException(ResultCode.BAD_REQUEST, "更新参数不能为空");
        }
        if (updateDTO.getId() == null) {
            throw new AdminException(ResultCode.BAD_REQUEST, "权限ID不能为空");
        }
    }
}
